const express = require('express');
const router = express.Router();
const Category = require('../models/category');

// 获取分类列表
router.get('/list', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, keyword } = req.query;
    const query = {};

    if (keyword) {
      query.name = new RegExp(keyword, 'i');
    }

    const total = await Category.countDocuments(query);
    const list = await Category.find(query)
      .skip((page - 1) * pageSize)
      .limit(Number(pageSize))
      .sort({ sort: 1, createdAt: -1 });

    res.status(200).json({
      code: 200,
      data: {
        list,
        total,
        page: Number(page),
        pageSize: Number(pageSize)
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取分类列表失败',
      error: error.message
    });
  }
});

// 获取单个分类详情
router.get('/detail', async (req, res) => {
  try {
    const { id } = req.query;
    if (!id) {
      return res.status(400).json({
        code:500,
        message: '分类ID不能为空'
      });
    }

    const category = await Category.findOne({ id });
    if (!category) {
      return res.status(404).json({
        code:500,
        message: '分类不存在'
      });
    }

    res.json({
      success: true,
      data: category
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: '获取分类详情失败'
    });
  }
});

// 创建分类
router.post('/create', async (req, res) => {
  try {
    // 生成唯一ID
    const timestamp = new Date().getTime();
    const random = Math.floor(Math.random() * 1000);
    const id = `${timestamp}${random}`;

    // 创建新分类，添加 id 字段
    const category = new Category({
      ...req.body,
      id
    });
    
    await category.save();

    res.status(200).json({
      code: 200,
      data: category,
      message: '创建成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '创建分类失败',
      error: error.message
    });
  }
});

// 更新分类
router.post('/update', async (req, res) => {
  try {
    const { id, ...updateData } = req.body;
    const category = await Category.findOneAndUpdate(
      { id },
      updateData,
      { new: true }
    );

    if (!category) {
      return res.status(404).json({
        code: 500,
        message: '分类不存在'
      });
    }

    res.status(200).json({
      code: 200,
      data: category,
      message: '更新成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '更新分类失败',
      error: error.message
    });
  }
});

// 删除分类
router.post('/delete', async (req, res) => {
  try {
    const { id } = req.body;
    const category = await Category.findOneAndDelete({ id });

    if (!category) {
      return res.status(404).json({
        code: 500,
        message: '分类不存在'
      });
    }

    res.status(200).json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '删除分类失败',
      error: error.message
    });
  }
});

// 添加一个测试路由
router.get('/test', (req, res) => {
  res.json({
    success: true,
    message: 'CORS is working'
  });
});

module.exports = router; 